package com.yocard.yxyd.ui.activity.base;

import android.content.Context;

import com.yocard.yxyd.base.CommonSubscriber;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.http.model.base.Response;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.utils.RxUtil;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.base.BasePresenter;
import com.yocard.yxyd.base.BaseView;
import com.yocard.yxyd.di.component.ActivityComponent;
import com.yocard.yxyd.di.component.DaggerActivityComponent;
import com.yocard.yxyd.di.module.ActivityModule;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import static com.yocard.yxyd.event.EventCode.REFRESH_TOKEN;

/**
 * Created on 2018/9/23.
 */
public abstract class BaseActivity<T extends BasePresenter> extends SimpleActivity implements BaseView {
    @Inject
    protected T mPresenter;

    protected ActivityComponent getActivityComponent() {
        return DaggerActivityComponent.builder()
                .appComponent(AppContext.getAppComponent())
                .activityModule(getActivityModule())
                .build();
    }

    protected ActivityModule getActivityModule() {
        return new ActivityModule(this);
    }

    protected void onViewCreated() {
        initInject();
        if (mPresenter != null)
            mPresenter.attachView(this);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        if (mPresenter != null)
            mPresenter.detachView();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void showErrorMsg(String msg) {
        dismisDialog();
        ToastUtils.showLong(msg);
    }

    @Override
    public void refreshTokenSucceed() {
        dismisDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFreshEvent(CommonBean bean) {
        if (bean.getCode() == REFRESH_TOKEN) {
            if (mPresenter != null)
                mPresenter.refreshToken();
        }
    }

    @Override
    public Context getContext() {
        return mContext;
    }


    protected abstract void initInject();
}
